<?php

class PublogController extends Controller
{

	public function accessRules()
	{
		return array(
				array('allow',  // allow all users to perform 'index' and 'view' actions
						'users'=>array('@'),
				),
				array('deny',  // deny all users
						'users'=>array('*')
				)
		);
	}
	
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}


	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			$row = Yii::app()->db->createCommand()->from('{{pub_log}} l')
				->where('l.logId='.$id)
				->join('{{host}} h', 'h.hostId=l.hostId')
				->queryAll();
			
			$ssh = new ESsh($row['host'], $row['port'], $row['username'], $row['password']);
			if ($ssh==null) return '无法连接发布主机';
			
			$archiveFile = $row['archivePath'].'/'.$row['archive'];
			$ssh->exec("/bin/rm -rf  $archiveFile");	//删除服务器上的
			@unlink(Yii::app()->params['archivesPath'].'/'.$row['archive']);	//删除本地的
			@unlink(Yii::app()->params['scriptPath'].'/'.$row['script']);	//删除本地脚本
			
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	public function actionRemove()
	{
		$uploadIds = $_POST['uploadIds'];
		$projectId = $_POST['projectId'];
		
		$rows = Yii::app()->db->createCommand()->from('{{pub_log}} l')
				->where('l.logId in ('. $uploadIds .')')
				->join('{{host}} h', 'h.hostId=l.hostId')
				->queryAll();
		if (count($rows)>0) {
			foreach($rows as $row) {
				$ssh = new ESsh($row['host'], $row['port'], $row['username'], $row['password']);
				if ($ssh==null) Tools::ajaxErrorReturn('无法连接发布主机');
				
				$archiveFile = $row['archivePath'].'/'.$row['archive'];
				$ssh->exec("/bin/rm -rf  $archiveFile");	//删除服务器上的
				@unlink(Yii::app()->params['archivesPath'].'/'.$row['archive']);	//删除本地的
				@unlink(Yii::app()->params['scriptPath'].'/'.$row['script']);	//删除本地脚本
				Yii::app()->db->createCommand()->delete('{{pub_log}}', 'logId=?', array($row['logId']));
			}
		}
		
		echo CJSON::encode(array());
		exit;
		
	}
	
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		//用户可用项目列表
		$projects= Project::model()->findAll(array(
				'with'=>array('users'),
				'condition'=>'users.userId = ?',
				'params'=>array(Yii::app()->user->userId)
		));	//用户可用项目
		
		if (count($projects)<=0) {
			throw new CHttpException('403', '你暂时没有被分配项目');
		}
		
		$projectListData = CHtml::listData($projects,'projectId','projectName');
		
		$defaultProjectId = Yii::app()->user->defaultProject;
		if ($defaultProjectId==0) $defaultProjectId = $projects[0]->projectId;
		$currentProjectId = Yii::app()->request->getParam('id', '0');
		$currentProjectId = $currentProjectId=='0' ? $defaultProjectId : $currentProjectId;	//当前项目id
		$currentProject = Project::model()->findByPk($currentProjectId);
		
		if (is_null($currentProject)) {
			throw new CHttpException('500', '无此项目');
		}

		
		$model=new PubLog('search');
		$model->unsetAttributes();  // clear any default values
		
		if(isset($_GET['PubLog']))
			$model->attributes=$_GET['PubLog'];
		
		$this->render('index',array(
				'model'=>$model,  //upload model
				'projects'=>$projects,
				'currentProject'=>$currentProject
		));

	}


	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=PubLog::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='log-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
